package state.socket;

import java.util.Vector;

import particle.core.tools.ByteBuffer;
import state.GameControl;
import state.util.SerialUtil;
import state.util.array.ByteArray;

public class WriterThread extends GameControl {
  private ByteBuffer outputStream = null;
  private Vector dataStack = new Vector();
  private int lastTimeSend = 0;
  private ClientConnection client = null;
  
  public WriterThread(ByteBuffer os1, ClientConnection client1) {
    this.outputStream = os1;
    this.client = client1;
    setTimeInterval(10);
    setRepeat(true);
    start();
    lastTimeSend = (int) System.currentTimeMillis();
  }

  private void writeBytes(ByteArray byteArray) {
    for (int i = 0; i < byteArray.len(); i++) {
      outputStream.appendByte(byteArray.get(i));
    }
    client.getSocket().send(outputStream);
    outputStream.clear();
  }

  public void perform() {
    if (!client.isConnectSuccess) {
      return;
    }
    
    while (dataStack.size() > 0) {
      DataPackage dataPackage = (DataPackage) dataStack.elementAt(0);
      dataStack.removeElementAt(0);
      ByteArray data = dataPackage.getAllData();
      writeBytes(SerialUtil.serialNumberFromInt(data.len()));
      writeBytes(data);
      client.getSocket().flush();
      lastTimeSend = (int) System.currentTimeMillis();
    }
  }

  public int getLastTimeSend() {
    return lastTimeSend;
  }

  public void write(DataPackage dataPackage) {
    dataStack.addElement(dataPackage);
  }

  public void detroy() {
    stop();
    dataStack = null;
    outputStream = null;
  }
}
